<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\BkController;
use App\Models\ResourceBk;
use App\Models\ResourceBusinessName;
use App\Models\ResourceTypeExternal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 博看科技
 */
class BkMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:BkMysqlData
    // 若使用 linux 后台执行则使用  nohup php artisan command:BkMysqlData &   //输入完后，关闭命令行
    // 或者使用 crontab 定时执行此命令行  */2 * * * * php /www/wwwroot/book/digital_reader_yzq/artisan command:XytsMysqlData

    protected $type_data_total = 200000; //每个类型数据总量
    protected $limit = 50; //每页限制条数
    protected $up_start_page = 1; //开始页，默认为 1
    protected $resource_business_id = 4; //资源商id

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:BkMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步博看科技数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('bkcmdlog')->debug('资源商不存在或已被删除');
            die;
        }
        try {
            //先同步类型
            $obj = new BkController();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $resourceModel = new ResourceBk();
            $bk_types = [1, 3]; //type： 1:期刊   3：图书
            foreach ($bk_types as $bk_type) {
                $data_type = $obj->getTypeList($bk_type);
                if ($data_type) {
                    $result_id = '';
                    foreach ($data_type['data'] as $key => $val) {
                        $val['class_type_id'] = $val['categoryId'];
                        $val['name'] = $val['categoryName'];
                        $val['resource_business_id'] = $this->resource_business_id;
                        $val['big_type_id'] = $bk_type == 1 ? 4 : 1; //4 为期刊 1为电子书
                        $result = $resourceTypeExternalModel->getTypeNameNoAdd($val);

                        $result_id .= $result . '、';
                    }
                    trim($result_id, '、');
                    Log::channel('bkcmdlog')->debug('博看数据类型 ' . $bk_type . ' 同步完成: ' . $result_id);
                }
            }

            //重新获取所有分类
            $self_type_all = $resourceTypeExternalModel->where('resource_business_id', $this->resource_business_id)->select('id', 'big_type_id', 'class_type_id', 'type_name')->where('is_del', 1)->get()->toArray();

            foreach ($self_type_all as $self_type) {
                $limit = $this->limit;
                $total = $this->type_data_total;
                $total_page = ceil($total / $limit) + 1;
                $data_unique_id_all = [];

                for ($i = 1; $i <= $total_page; $i++) {
                    $bk_type = $self_type['big_type_id'] == 4 ? 1 : 3; //转换为博看的 图书 1， 期刊 3
                    $data = $obj->getBookList($bk_type, $self_type['class_type_id'], $i, $limit); //获取总数据
                    if ($data) {
                        $result_id = '';
                        foreach ($data['data'] as $key => $val) {
                            $data_unique_id_all[] = $val['resourceId']; //记录现有所有数据的id
                            //获取数据详情
                            $val['type_id'] = $self_type['id'] ?? null; //获取我们数据库的类型id
                            $val['big_type_id'] = $self_type['big_type_id']; //4 为期刊 1为电子书
                            $result = $resourceModel->addData($val);
                            $result_id .= $result . '、';
                        }
                        trim($result_id, '、');
                        Log::channel('bkcmdlog')->debug('全量同步上架数据, 类型ID: ' . $self_type['class_type_id'] . '; 类型名称：' . $self_type['type_name'] . '; 第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                    } else {
                        //下架列表，除这些之外的数据全部下架
                        $resourceModel->deleteData($self_type['id'], $data_unique_id_all);

                        Log::channel('bkcmdlog')->debug('全量同步上架数据处理完毕, 类型ID: ' . $self_type['class_type_id'] . '; 类型名称：' . $self_type['type_name'] . '; 页数: ' . $i);
                        break;
                    }
                }
            }
            Log::channel('bkcmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
              //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('bkcmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
